import asyncio
import random
from pyppeteer import launch
import cv2
import urllib.request
def get_dis(bg,fg):
	img = cv2.imread(bg)
	temp = cv2.imread(fg)
	res = cv2.matchTemplate(img,temp,cv2.TM_CCORR_NORMED)
	value = cv2.minMaxLoc(res)[2][0]
	dis = value * 342 / 360
	return dis

async def login():
	browser = await launch({
		'headless': False,
		'args': ['--window-size=1920,1080']

	})
	page = await browser.newPage()

	await page.setViewport({'width': 1920, 'height': 1080})

	await page.goto('https://passport.jd.com/new/login.aspx')

	# 点击切换  账户登录
	await page.click('#pwd-login')

	# 填写用户名
	await page.type('#loginname', '18323406700', {
		'delay': random.randint(60, 100)
	})

	await page.type('#nloginpwd', 'lijin1234', {
		'delay': random.randint(60, 100)
	})

	# 延时
	await page.waitFor(2000)
	await page.click('div.login-btn')
	await page.waitFor(2000)

	# 定位图片 进行缺口识别
	# 归一化平方差匹配
	# 进行距离移动
	img_src = await page.Jeval('.JDJRV-bigimg > img','el => el.src')
	urllib.request.urlretrieve(img_src,'image.png')

	temp_src = await page.Jeval('.JDJRV-smallimg > img','el => el.src')
	urllib.request.urlretrieve(temp_src,'temp_src.png')

	# 缺口识别
	dis = get_dis('image.png','temp_src.png')
	print(dis)
	# 拖动滑块
	el = await page.J('div.JDJRV-slide-btn')
	box = await el.boundingBox()
	await  page.hover('div.JDJRV-slide-btn')

	# 按下鼠标
	await page.mouse.down()
	x1 = box['x'] + dis + random.uniform(1, 5)

	await page.mouse.move(x1, box['y'], {'steps': 30})
	await page.waitFor(random.randint(100, 300))
	await page.mouse.move(box['x'] + dis + 27, box["y"], {'steps': 30})
	# 松开鼠标
	await page.mouse.up()
	await page.waitFor(2000)

	# 获取cookies
	cookies = await page.cookies()

	# 打印cookies
	with open('config.txt', 'w', encoding='utf-8') as js_file:
		js_file.write(str(cookies))
	print('登录成功! ')



asyncio.run(login())
